/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.module.dict.api.aop;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.elsfs.cloud.common.annotations.Dict;

/** 反射缓存类 */
@Slf4j
class ReflectionCache {
  private static final Map<Class<?>, List<Field>> annotatedFieldsCache = new ConcurrentHashMap<>();
  private static final Map<Class<?>, Map<String, Field>> fieldCache = new ConcurrentHashMap<>();

  private ReflectionCache() {}

  static List<Field> getAnnotatedFields(Class<?> clazz) {
    return annotatedFieldsCache.computeIfAbsent(
        clazz,
        c ->
            Arrays.stream(c.getDeclaredFields())
                .filter(f -> Objects.nonNull(f.getAnnotation(Dict.class)))
                .collect(Collectors.toList()));
  }

  /**
   * 尝试从给定的类中获取指定字段名的字段。首先从一个缓存（fieldCache）中查找，如果缓存中不存在，则尝试从类中声明的字段中获取。
   * 如果字段存在，则将其加入缓存并返回；如果字段不存在或出现异常，则返回null。
   *
   * @param clazz 要查找字段的类
   * @param fieldName 要查找的字段名
   * @return 返回找到的字段，如果未找到或出现异常则返回null
   */
  static Field getCachedDeclaredField(Class<?> clazz, String fieldName) {
    try {
      // 在fieldCache中分两步查找或初始化：首先查找或初始化clazz对应的ConcurrentHashMap，然后在该ConcurrentHashMap中查找或初始化fieldName对应的Field
      return fieldCache
          .computeIfAbsent(clazz, c -> new ConcurrentHashMap<>())
          .computeIfAbsent(
              fieldName,
              f -> {
                try {
                  return clazz.getDeclaredField(f); // 尝试获取声明的字段
                } catch (NoSuchFieldException e) {
                  throw new RuntimeException(e.getMessage());
                }
              });
    } catch (RuntimeException e) {
      LOGGER.error("Failed to find field '{}' in class {}", fieldName, clazz.getName(), e);
    }
    return null; // 出现异常或未找到字段时返回null
  }
}
